package AdminService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/grand"
	"time"
)

func Add(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	data["create_at"] = time.Now().Unix()
	data["dept_id"] = r.GetInt64("departmentId", 0)

	// 禁止 account 重复
	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "admin").Where("account",
		data["account"]).Fields("id").Count()
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	if count > 0 {
		return response.FailByRequestMessage(r, "账号重复")
	}

	// 增加附加数据
	if req.AddInsertData != nil {
		otherData := req.AddInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 添加前方法
	if req.AddBeforeFn != nil {
		respRes := req.AddBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	// 增加默认密码
	passwordSalt := grand.Letters(10)
	defaultPassword := "123456"
	data["password_salt"] = passwordSalt
	data["password"] = tools.EncryptPassword(defaultPassword, passwordSalt)
	tx, err := g.DB().Ctx(ctx).Begin()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	obj := tx.Model(req.TableName).Unscoped()
	id, err := obj.Fields(obj.GetFieldsStr()).InsertAndGetId(data)
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}

	roleIdList := r.GetArray("roleIdList")

	// 插入 admin_role
	if roleIdList != nil {
		rmData := g.List{}
		for _, item := range roleIdList {
			rmData = append(rmData, g.Map{
				"admin_id": id,
				"role_id":  item,
			})
		}
		if len(rmData) > 0 {
			res, err := tx.Model("admin_role").Insert(rmData)
			if err != nil {
				tx.Rollback()
				return response.FailByRequestMessage(nil, err.Error())
			}
			row, err := res.RowsAffected()
			if err != nil {
				tx.Rollback()
				return response.FailByRequestMessage(nil, err.Error())
			}
			if row < 1 {
				tx.Rollback()
				return response.FailByRequestMessage(nil, "添加失败")
			}
		}
	}

	tx.Commit()
	return response.SuccessByRequestMessageData(nil, "添加成功", g.Map{
		"id": id,
	})
}
